<template>
    <view class="content">
        <show-modal></show-modal>

        <view class="bg-img bg-mask flex align-center" style="background-image: url('https://jzy-sup3-dev.oss-cn-shanghai.aliyuncs.com/chik/static/member_top.jpg');
                height: 500upx;">
            <view class="padding text-white" style="width:100%">
                <view v-if="loginState===1" class="flex p-xs margin-bottom-sm mb-sm">
                    <view class="flex-twice padding-sm margin-xs radius">
                        <view class="padding-xs text-xxl text-bold">
                            {{nickname}}
                        </view>
                        <view class="padding-xs text-lg">
                            一定要好好吃饭.
                        </view>
                    </view>
                    <view class="flex-sub padding-sm margin-xs radius" style="margin-top:auto">
                        <view class="cu-avatar xl round flow-box" :style="{'background-image':'url('+avatar+')'}">
                        </view>
                    </view>
                </view>

                <view v-if="loginState===1" class="flex p-xs margin-bottom-sm mb-sm">
                    <view class="flex-twice margin-left-sm padding-left-xs">
                        <view class="padding-xs display-inline">
                            关注：9
                        </view>
                        <view class="padding-xs display-inline">
                            粉丝：10
                        </view>
                    </view>
                    <view class="flex-sub">
                        <view class="padding-xs display-inline">
                            积分：{{point}}
                        </view>
                    </view>
                </view>

                <view v-if="loginState===0" class="flex p-xs margin-bottom-sm mb-sm">
                    <view class="flex-twice margin-left-sm padding-left-xs">
                        <button class="cu-btn " @click="updateUserInfo">
                            <text class="cuIcon-exit lg text-black"></text>
                            <text class="text-black">登录</text>
                        </button>
                    </view>
                </view>
            </view>
        </view>

        <view class="cu-list menu" :class="'card-menu margin-top'">
            <view class="cu-item" :class="'arrow'">
                <view class="content">
                    <text class="cuIcon-squarecheckfill text-green"></text>
                    <text class="text-grey">签到 + 积分商城兑换（暂未实现）</text>
                </view>
            </view>
            <view class="cu-item" :class="'arrow'" @click="myCollect">
                <view class="content">
                    <text class="cuIcon-favorfill text-orange"></text>
                    <text class="text-grey">我的收藏</text>
                </view>
            </view>
            <view class="cu-item" :class="'arrow'">
                <navigator class="content" hover-class="none" url="../book/works" open-type="navigate">
                    <text class="cuIcon-camerafill text-pink"></text>
                    <text class="text-grey">我的作品</text>
                </navigator>
            </view>
            <view class="cu-item" :class="'arrow'">
                <button class="cu-btn content" open-type="contact">
                    <text class="cuIcon-servicefill text-gray"></text>
                    <text class="text-grey">反馈与建议</text>
                </button>
            </view>
            <view class="cu-item" :class="'arrow'" v-if="phone == '13609245992'">
                <navigator class="content" hover-class="none" url="../book/publish" open-type="navigate">
                    <text class="cuIcon-add text-red"></text>
                    <text class="text-grey">发布作品</text>
                </navigator>
            </view>
            
            <!-- #ifdef MP-TOUTIAO -->
            <!-- <view class="cu-item" :class="'arrow'">
                <button class="cu-btn content" @click="openAwemeUserProfile">
                    <text class="cuIcon-roundclosefill text-gray"></text>
                    <text class="text-grey">关注我们</text>
                </button>
            </view>
            <view class="cu-item" :class="'arrow'">
                <button class="cu-btn content" @click="subscribeMessage">
                    <text class="cuIcon-roundclosefill text-gray"></text>
                    <text class="text-grey">订阅菜谱更新</text>
                </button>
            </view> -->
            <!-- #endif -->

            <view class="cu-item" :class="'arrow'">
                <button class="cu-btn content" @click="logout">
                    <text class="cuIcon-roundclosefill text-gray"></text>
                    <text class="text-grey">退出登录</text>
                </button>
            </view>
        </view>
    </view>
</template>

<script>
    import {
        TRADE_METHOD,
        STD_AUTH_PROVIDER
    } from '@/common/vmeitime-http/const.js'
    export default {
        data() {
            return {
                loginState: 0,

                avatar: "",
                nickname: "",
                point: "10",
                phone: "",

                inviteuum: 0,
                userList: []
            }
        },
        onReady() {
            uni.setNavigationBarTitle({
                title: '我的主页'
            })
            uni.setNavigationBarColor({
                frontColor: '#FFF',
                backgroundColor: '#141414'
            })
        },
        mounted() {
            console.log('user mounted')
            let that = this;
            uni.checkSession({
                success: function(t) {
                    console.log("没过期");
                    that.queryUserInfo();
                },
                fail: function() {
                    console.log("过期了");
                    that.loginState = 0;

                    uni.showLoading({
                        mask: true,
                        title: '授权登录中...',
                    })
                    let baseAuthCode = uni.getStorageSync("baseAuthCode");
                    if (!baseAuthCode) {
                        that.$api.baseToken().then(() => {
                            uni.hideLoading();
                        });
                        return;
                    }
                    that.$api.baseLogin(baseAuthCode).then(() => {
                        uni.hideLoading();
                        that.queryUserInfo();
                    });
                }
            });
        },
        methods: {
            queryUserInfo: function() {
                this.loading = true
                this.$api.userInfo({}).then((res) => {
                    this.loading = false;
                    console.log("接口中用户信息", res)

                    // 默认不是会员，也没有到期时间
                    this.avatar = res.data.avatar;
                    this.nickname = res.data.nickName;
                    this.point = res.data.point;
                    this.phone = res.data.phone;

                    let userInfo = uni.getStorageSync('userInfo');
                    console.log("缓存中用户信息", userInfo, res.data);
                    userInfo.memberInfo = res.data;
                    uni.setStorageSync('userInfo', userInfo);

                    if (res.data.nickName != null) {
                        this.loginState = 1;
                    }
                }).catch((err) => {
                    this.loading = false;
                    console.error('request fail', err);
                })
            },
            updateUserInfo: function() {
                let that = this;
                let userInfo = {}
                let authType = STD_AUTH_PROVIDER.WECHAT.NAME;
                // #ifdef MP-TOUTIAO
                authType = STD_AUTH_PROVIDER.TOUTIAO.NAME;
                // #endif
                debugger
                uni.getUserProfile({
                    desc: "区分登录用户",
                    provider: authType,
                    success: function(wxInfo) {
                        console.log("wxInfo", wxInfo);
                        userInfo.wxInfo = wxInfo.userInfo;
                        uni.setStorageSync('userInfo', userInfo);
                        // 绑定会员信息
                        let inviteOpenid = uni.getStorageSync("invite_openid");
                        let requestData = {};
                        Object.assign(requestData, {
                            signature: wxInfo.signature,
                            rawData: wxInfo.rawData,
                            encryptedData: wxInfo.encryptedData,
                            iv: wxInfo.iv,
                            inviteOpenid: inviteOpenid
                        });
                        that.$api.bindOpenUser(requestData).then((res) => {
                            that.loginState = 1;
                            userInfo.memberInfo = res.data;
                            uni.setStorageSync('userInfo', userInfo);
                            that.queryUserInfo();
                        });
                    },
                    fail: function(err) {
                        console.error("getUserProfile fail1", err)
                    }
                });
            },
            logout: function() {
                this.loginState = 0;
            },
            openAwemeUserProfile: function() {
                let isCanUseMedia = tt.canIUse("openAwemeUserProfile");
                console.log("canUse", isCanUseMedia);
                if (!isCanUseMedia) {
                    uni.showToast({
                        title: "该功能不可用，请在抖音中使用",
                        icon: "none"
                    })
                    return
                }
                tt.openAwemeUserProfile({
                    success: (res) => {
                        console.log(res);
                    },
                });
            },
            subscribeMessage() {
                tt.requestSubscribeMessage({
                    tmplIds: ["MSG1307883d1553358c484a0ac2d4f1a515567d87915647"], // 需要填入开放平台申请的模版id，支持最多3个同类型模版
                    success(res) {
                        //订阅成功
                        console.log("订阅成功", res);
                        tt.showToast({
                            title: "订阅成功",
                            icon: "success",
                        });
                    },
                    fail(error) {
                        //订阅失败
                        console.log("订阅失败, 错误详情: ", error);
                        tt.showToast({
                            title: "订阅失败",
                            icon: "fail",
                        });
                    },
                });
            },
            myCollect: function() {
                uni.navigateTo({
                    url: "/pages/user/collect"
                })
            },
        }
    }
</script>

<style lang="less">
    .display-inline {
        display: inline-block;
    }

    .cu-list.menu>.cu-item .content {
        margin-bottom: 5px;
    }
</style>
